<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
    <!-- 主要内容 -->
    <main class="flex-1 overflow-x-hidden overflow-y-auto  p-6 bg-gray-100">
        <div class="bg-white rounded-lg  p-6">
            <!-- 搜索筛选区 -->
            <div class="flex items-center space-x-4 mb-6">
                <el-input v-model="searchQuery" placeholder="请输入题型名称" class="w-64" />
                <el-select v-model="selectedType" placeholder="题型描述" class="w-40">
                    <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-select v-model="selectedMajor" placeholder="题型专业" class="w-40">
                    <el-option v-for="item in majorOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-button type="primary" @click="handleSearch" class="!rounded-button whitespace-nowrap">搜索</el-button>
                <el-button @click="handleReset" class="!rounded-button whitespace-nowrap">重置</el-button>
            </div>
            <!-- 操作按钮区 -->
            <div class="flex space-x-4 mb-6">
                <el-button type="primary" class="!rounded-button" @click="openDialog('add')">
                    <el-icon class="mr-1">
                        <Plus />
                    </el-icon>新增
                </el-button>
                <el-button type="danger" class="!rounded-button whitespace-nowrap" @click="handleDelete">
                    <el-icon class="mr-1">
                        <Delete />
                    </el-icon>删除
                </el-button>
                <el-button type="success" class="!rounded-button" @click="handleImport">
                    <el-icon class="mr-1">
                        <Upload />
                    </el-icon>导入
                </el-button>
                <el-button type="warning" class="!rounded-button" @click="handleExport">
                    <el-icon class="mr-1">
                        <Download />
                    </el-icon>导出
                </el-button>
            </div>
            <!-- 数据表格 -->
            <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="id" label="题库编号" width="120" />
                <el-table-column prop="assessmentName" label="题库名称" width="180" />
                <el-table-column prop="assessmentDescription" label="题库描述" />
                <el-table-column prop="major" label="题库专业" width="120" />
                <el-table-column prop="createTime" label="创建时间" width="180" :formatter="formatDate"/>
                <el-table-column label="操作" width="240">
                    <template #default="scope">
                        <div class="flex space-x-2">
                            <el-button size="small" @click="openDialog('edit', scope.row)"
                                class="!rounded-button whitespace-nowrap w-16">编辑</el-button>
                            <el-button size="small" type="danger" @click="handleDelete(scope.row)"
                                class="!rounded-button whitespace-nowrap w-16">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页控件 -->
            <div class="flex items-center justify-between mt-6">
                <span class="text-sm text-gray-500">共 {{ total }} 条</span>
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </div>
    </main>

    <!-- 新增题库弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增题库' : '编辑题库'" width="500px" destroy-on-close>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="题库名称" prop="typeName">
                <el-input v-model="form.assessmentName" placeholder="请输入题库名称" />
            </el-form-item>
            <el-form-item label="题库描述" prop="description">
                <el-input type="textarea" v-model="form.assessmentDescription" placeholder="请输入题库描述"
                          :autosize="{ minRows: 2, maxRows: 6 }" />
            </el-form-item>
            <el-form-item label="题库专业" prop="type">
                <el-input type="textarea" v-model="form.major" placeholder="请输入题库专业"
                          :autosize="{ minRows: 2, maxRows: 6 }" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit()">确认</el-button>
            </span>
        </template>
    </el-dialog>
<!--    /编辑题库弹窗-->
    <el-dialog v-model="dialogVisible1" :title="dialogType === 'add' ? '新增题库' : '编辑题库'" width="500px" destroy-on-close>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="题库名称" prop="typeName">
                <el-input v-model="form.assessmentName" placeholder="请输入题库名称" />
            </el-form-item>
            <el-form-item label="题库描述" prop="description">
                <el-input type="textarea" v-model="form.assessmentDescription" placeholder="请输入题库描述"
                          :autosize="{ minRows: 2, maxRows: 6 }" />
            </el-form-item>
            <el-form-item label="题库专业" prop="type">
                <el-input type="textarea" v-model="form.major" placeholder="请输入题库专业"
                          :autosize="{ minRows: 2, maxRows: 6 }" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible1 = false">取消</el-button>
                <el-button type="primary" @click="update()">确认</el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 上传文件弹窗 -->
    <el-upload ref="upload" :action="uploadUrl" :before-upload="beforeUpload" :on-success="handleUploadSuccess"
        :on-error="handleUploadError" accept=".xls,.xlsx" show-file-list="false" :auto-upload="false">
    </el-upload>
</template>

<script lang="ts" setup>
import { ref,onMounted } from 'vue';
import * as XLSX from "xlsx";  // 引入 xlsx 库
import {getAssessmentTypeList,addAssessmentType,updateAssessmentType,deleteAssessmentType,deleteAssessmentTypes} from "../../api/admin/topic"
import { FormInstance, FormRules, ElMessageBox, ElMessage } from "element-plus";
import { Search, Bell, FullScreen, Plus, Upload, Download, Expand } from '@element-plus/icons-vue';
// 搜索相关
const searchQuery = ref('');
const selectedType = ref('');
const selectedMajor = ref('');
const selectedDifficulty = ref('');
onMounted(()=>{
    const data={
        page:currentPage.value,
        pagesize:pageSize.value,
    }
   getList(data,null)
})

// 日期格式化方法
const formatDate = (row, column, cellValue) => {
    if (!cellValue) return '';
    const d = new Date(cellValue);
    return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`; // 返回 yyyy-mm-dd 格式
};
//获取列表
async function getList(data,listAssessmentTypeDto) {
    await getAssessmentTypeList(data,listAssessmentTypeDto).then(function (response) {
        tableData.value=response.rows
        total.value=response.total
    })
}
// 下拉选项

// 选中的行的ID数组
const selectedRowKeys = ref([]);

const handleSelectionChange = (selection) => {
    selectedRowKeys.value = selection.map(item => item.id);
};

const typeOptions = [
    { value: 'single', label: '单选题' },
    { value: 'multiple', label: '多选题' },
    { value: 'judge', label: '判断题' },
];
const majorOptions = [
    { value: 'software', label: '软件工程' },
    { value: 'network', label: '网络工程' },
    { value: 'ai', label: '人工智能' },
];
const difficultyOptions = [
    { value: 'easy', label: '简单' },
    { value: 'medium', label: '中等' },
    { value: 'hard', label: '困难' },
];
// 表格数据
let tableData = ref([]);
// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);
const handleSizeChange = (val: number) => {
    pageSize.value = val;
    ElMessage.info(`每页显示 ${val} 条`);
};
const handleCurrentChange = (val: number) => {
    currentPage.value = val;
    ElMessage.info(`当前页：${val}`);
};

// 处理函数
const handleSearch = () => {
    const data={
        page:currentPage.value,
        pagesize:pageSize.value,

    }
    const listAssessmentTypeDto={
        name:searchQuery.value,
            description:selectedType.value,
            major:selectedMajor.value
    }
    getList(data,listAssessmentTypeDto)
    ElMessage.success('执行搜索操作');
};
const handleReset = () => {
    searchQuery.value = '';
    selectedType.value = '';
    selectedMajor.value = '';
    selectedDifficulty.value = '';
    ElMessage.info('重置搜索条件');
};

// 弹窗相关
const dialogVisible = ref(false);
const dialogVisible1 = ref(false);
const dialogType = ref('');
const formRef = ref<FormInstance>();
//弹框表单
let form = ref({
    id:0,
    assessmentName: '',       // 题型名称
    assessmentDescription: '',    // 题型描述
    major: null          // 题型类型，1=专业题型，2=非专业题型
});


function openDialog(type: string, row?: any) {
    dialogType.value = type;
    if (type === 'edit') {
        dialogVisible1.value = true;
        console.log(row)
        // 手动赋值字段
        form.value.id=row.id ;
        form.value.assessmentName = row.assessmentName ; // 题型名称
        form.value.assessmentDescription = row.assessmentDescription ; // 题型描述
        form.value.major = row.major ; // 根据类型映射到表单值
        console.log(form.value)
    }if (type === 'add'){
        dialogVisible.value= true
        // 重置表单
        form.value = {
            id:0,
            typeName: '',
            description: '',
            type: null
        };
    }
};


//提交
function handleSubmit () {
    console.log(form)
    addAssessmentType(form.value)
    dialogVisible.value = false;
    ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功');
    getList()
};
function update() {
    updateAssessmentType(form.value)
    dialogVisible1.value = false;
    getList()
}
//删除用户
const handleDelete = (row: any) => {
    // 获取当前选中的行
   const selectedRows = tableData.value.filter(row => selectedRowKeys.value.includes(row.id));
    let data=[]
    if (selectedRows.length === 0) {
        ElMessage.warning('请至少选择一项进行删除');
        return;
    }

    ElMessageBox.confirm(
        '确定要删除选中的题型吗？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 删除操作
        if (selectedRows.length <=1){
            deleteAssessmentType(row)
        }else {
            selectedRows.forEach(row => {
                data.push(row.id)
            });
            deleteAssessmentTypes(data)
        }
        getList()
        ElMessage.success('删除成功');
    }).catch(() => { });
};

// 导入功能
const handleImport = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.xlsx, .xls';
    input.onchange = (e: any) => {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = (event: any) => {
                const data = event.target.result;
                const wb = XLSX.read(data, { type: 'array' });
                const ws = wb.Sheets[wb.SheetNames[0]];
                const json = XLSX.utils.sheet_to_json(ws, { header: 1 });
                console.log('导入数据:', json);
                // 假设你将数据存入 tableData
                tableData.value = json.slice(1).map((row: any) => {
                    return {
                        id: row[0],
                        username: row[1],
                        nickname: row[2],
                        phone: row[3],
                        account: row[4],
                        address: row[5],
                        status: row[6] === '启用', // 状态转换
                        createTime: row[7]
                    };
                });
                ElMessage.success('文件导入成功');
            };
            reader.readAsArrayBuffer(file);
        }
    };
    input.click();
};

// 导出功能
const handleExport = () => {
    const ws = XLSX.utils.json_to_sheet(tableData.value);  // 将 tableData 转为 sheet
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    const data = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = window.URL.createObjectURL(data);
    const link = document.createElement('a');
    link.href = url;
    link.download = '用户数据.xlsx';  // 设置下载的文件名
    link.click();
    ElMessage.success('文件导出成功');
};
</script>
<style scoped>
/* 移除 input type="number" 的默认箭头 */
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

input[type="number"] {
    -moz-appearance: textfield;
}

/* 确保按钮文字不换行 */
.el-button {
    white-space: nowrap;
}

/* 自定义样式 */
.question-management-system {
    font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
}
</style>
